package com.woniu.sharepark.listener;

import com.woniu.sharepark.common.pojo.Login;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.HashMap;

/**
 * 单态登录
 * @author zy
 * @date 2019/6/18 19:01
 */

@WebListener
public class SingleStateListener implements HttpSessionAttributeListener{


    private HashMap<String, HttpSession> session = new HashMap<String, HttpSession>();
    @Override
    public void attributeAdded(HttpSessionBindingEvent se){

        String name = se.getName();

        if (name.equals("currentUser")){
            Login login = (Login) se.getValue();
            String lAccount = login.getlAccount();

           //获取当前用户的session对象
           HttpSession currentSession = se.getSession();

           //获取当前用户之前登录的session对象
            HttpSession oldSession = session.get(lAccount);

            if (oldSession!=null && !(oldSession.getId().equals(currentSession.getId()))){

                oldSession.invalidate();
            }
            session.put(lAccount,currentSession);

        }

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
    }
}
